import * as React from 'react';
import { useEffect, useRef, useState } from 'react';
import { SafeAreaView } from 'react-native-safe-area-context';
import { Pressable, StyleSheet, Text, View } from 'react-native';
import {
  FontAwesome5,
  MaterialCommunityIcons,
  MaterialIcons,
} from '@expo/vector-icons';
import { Video } from 'expo-av';
import { useRoute } from '@react-navigation/native';
import BackButton from '../../navigation/BackButton';
import CameraVideo from '../../components/CameraVideo';
import { RootStackRouteProp } from '../../types';
import { courseList } from '../../constants/DataList';

export default function VideoCourseScreen() {
  const route = useRoute<RootStackRouteProp<'VideoCourse'>>();

  const videoRef = useRef<Video>(null);
  const [isPlaying, setPlaying] = useState(false);
  const [playbackStatus, setPlaybackStatus] = useState({});
  const [progressWidth, setProgressWidth] = useState(0);
  const [currentTime, setCurrentTime] = useState('00:00');

  const { courseId, recordSelf } = route.params;

  const course = courseList.find(it => it.id === courseId);

  useEffect(() => {
    const {
      isLoaded,
      durationMillis = 0,
      positionMillis = 0,
      didJustFinish,
      isPlaying: isActualPlaying,
    } = playbackStatus as any;

    setPlaying(isActualPlaying);

    if (!isLoaded || durationMillis === 0) {
      setProgressWidth(0);
      setCurrentTime('00:00');
    } else {
      setProgressWidth((positionMillis / durationMillis) * 100);

      const minutes = Math.floor(positionMillis / 1000 / 60);
      const seconds = Math.floor(positionMillis / 1000) % 60;
      const minutesStr = String(minutes).padStart(2, '0');
      const secondsStr = String(seconds).padStart(2, '0');
      setCurrentTime(`${minutesStr}:${secondsStr}`);
    }

    if (didJustFinish) {
      videoRef?.current?.setPositionAsync(0);
      videoRef?.current?.pauseAsync();
    }
  }, [playbackStatus]);

  const togglePlay = () => {
    if (isPlaying) {
      videoRef?.current?.pauseAsync();
    } else {
      videoRef?.current?.playAsync();
    }
  };

  if (!course) {
    return <View />;
  }

  return (
    <SafeAreaView style={styles.safeArea}>
      <View style={styles.container}>
        <BackButton />

        {recordSelf && <CameraVideo style={styles.selfVideo} />}

        <Video
          ref={videoRef}
          style={styles.courseVideo}
          shouldPlay={true}
          onPlaybackStatusUpdate={setPlaybackStatus}
          source={{
            uri: course.video,
          }}
        />

        <View style={styles.activityContainer}>
          <Text style={styles.time}>{currentTime}</Text>
          <View style={styles.activityInfo}>
            <MaterialCommunityIcons name="heart-pulse" size={24} color="red" />
            <Text style={styles.activityText}>140</Text>
          </View>
          <View style={styles.activityInfo}>
            <MaterialIcons name="local-fire-department" size={24} color="red" />
            <Text style={styles.activityText}>41千卡</Text>
          </View>
        </View>

        <View style={styles.videoControl}>
          <View
            style={[styles.videoProgress, { width: `${progressWidth}%` }]}
          />
          <Pressable style={styles.playPause} onPress={togglePlay}>
            {isPlaying ? (
              <FontAwesome5 name="pause" size={24} color="#333" />
            ) : (
              <FontAwesome5 name="play" size={24} color="#333" />
            )}
          </Pressable>
        </View>
      </View>
    </SafeAreaView>
  );
}

const styles = StyleSheet.create({
  safeArea: {
    flex: 1,
    backgroundColor: '#000000',
  },
  container: {
    flex: 1,
    justifyContent: 'center',
  },
  courseVideo: {
    flex: 1,
  },
  selfVideo: {
    height: 210,
    width: 160,
    position: 'absolute',
    right: 12,
    top: 12,
    zIndex: 1,
  },
  activityContainer: {
    position: 'absolute',
    right: 12,
    left: 12,
    bottom: 100,
    flexDirection: 'row',
  },
  time: {
    fontSize: 24,
    fontWeight: '500',
    color: '#ffffff',
    textShadowColor: '#777777',
    textShadowOffset: { width: 1, height: 1 },
    textShadowRadius: 3,
    marginRight: 'auto',
  },
  activityInfo: {
    flexDirection: 'row',
    alignItems: 'center',
    paddingHorizontal: 6,
  },
  activityText: {
    color: '#fff',
    fontSize: 18,
    fontWeight: 'bold',
    paddingHorizontal: 6,
    minWidth: 50,
  },
  videoControl: {
    position: 'absolute',
    bottom: 48,
    left: 12,
    right: 12,
    height: 42,
    backgroundColor: '#eee',
    borderRadius: 8,
    overflow: 'hidden',
    alignItems: 'center',
  },
  videoProgress: {
    position: 'absolute',
    left: 0,
    height: '100%',
    width: '20%',
    backgroundColor: '#60c48e',
  },
  playPause: {
    height: '100%',
    width: 50,
    justifyContent: 'center',
    alignItems: 'center',
  },
});
